package com.pcbly.web.persistence.user;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.apache.commons.lang.StringUtils;

import com.pcbly.web.bean.system.AuthorityBean;
import com.pcbly.web.bean.system.GroupBean;
import com.pcbly.web.bean.user.UserBean;
import com.pcbly.web.bean.user.UserDetailBean;
import com.pcbly.web.components.utils.LightsoftStringUtils;
import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.components.utils.security.MD5;
import com.pcbly.web.persistence.HibernateBaseDao;

@SuppressWarnings("unchecked")
public class UserHibernateDao extends HibernateBaseDao<UserBean> implements
		UserDao {

	public UserHibernateDao() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 4541060028292301825L;

	protected Class<UserBean> getEntityClass() {
		return UserBean.class;
	}

	/**
	 * 通过用户名密码获取用户
	 */

	public UserBean findUserBeanByUserAndPasswd(String user, String passwd)
			throws Exception {
		// TODO Auto-generated method stub
		String hsql = "from UserBean where userName=? and passwd=?";
		List<UserBean> list = getHibernateTemplate().find(hsql,
				new Object[] { user, passwd });
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}

	}

	/**
	 * 通过UserBean找出其相对应的所有合法的AuthorityBean
	 */
	public List<AuthorityBean> findAuthByUserBean(UserBean user)
			throws Exception {
		String hql = "select permi from AuthorityBean permi inner join permi.roles as role "
				+ " inner join role.users as user where permi.status='1' and user=?";
		return getHibernateTemplate().find(hql, user);
	}

	/**
	 * 通过Permission找出其相对应的所有合法的users
	 */
	public List<UserBean> findUsersByAuthorityBean(AuthorityBean permi)
			throws Exception {
		String hql = "select user from AuthorityBean permi inner join permi.roles as role "
				+ " inner join role.users as user where permi.status='1' and permi=?";
		return getHibernateTemplate().find(hql, permi);
	}

	public UserBean getUserByLoginName(String userName) throws Exception {
		// TODO Auto-generated method stub
		String hsql = "from UserBean where userName=?";
		List<UserBean> list = getHibernateTemplate().find(hsql,
				new Object[] { userName });
		if (list.isEmpty()) {
			return null;
		} else {
			return list.get(0);
		}
	}

	public List<UserBean> findBy(Map<String, String> filter) throws Exception {
		Criteria criteria = getEntityCriteria();

		String id = filter.get("id");
		if (StringUtils.isNotBlank(id))
			criteria.add(Restrictions.eq("id", id));

		String name = filter.get("nickName");
		if (StringUtils.isNotBlank(name))
			criteria.add(Restrictions.like("nickName", "%" + name + "%"));

		String loginid = filter.get("userName");
		if (StringUtils.isNotBlank(loginid))
			criteria.add(Restrictions.like("userName", "%" + loginid + "%"));

		String email = (String) filter.get("email");
		if (StringUtils.isNotBlank(email))
			criteria.add(Restrictions.like("email", "%" + email + "%"));

		String status = (String) filter.get("status");
		if (StringUtils.isNotEmpty(status) && !"all".equals(status))
			criteria.add(Restrictions.eq("status", status));

		criteria.addOrder(org.hibernate.criterion.Order.asc("id"));

		return criteria.list();
	}

	@Override
	public UserBean getUserBeanById(String id) throws Exception {
		// TODO Auto-generated method stub
		UserBean bean = (UserBean) getSession().createQuery(
				"from UserBean where id=?").setString(0, id).uniqueResult();
		// String sql = "select DISTINCT a.* from sys_user_school a right join
		// sys_user b on a.USERID=b.ID where b.id=?";
		// List<UserSchoolBean> schools = getSession().createSQLQuery(sql)
		// .addEntity(UserSchoolBean.class).setString(0, id).list();
		// System.out.println(schools.size());
		// if (schools.isEmpty()) {
		// schools = new ArrayList<UserSchoolBean>(0);
		// }
		// for(UserSchoolBean school:schools){
		// System.out.println(school.getId());
		// System.out.println(school.getDegree());
		// System.out.println(school.getCreateUserId());
		// }
		// bean.setUserSchools(new HashSet(java.util.Arrays.asList(schools)));

		// sql = "select DISTINCT a.* from sys_user_detail a right join sys_user
		// b on a.ID=b.ID where b.id=?";
		// Object object = getSession()
		// .createSQLQuery(sql).addEntity(UserDetailBean.class).setString(
		// 0, id).uniqueResult();
		// UserDetailBean userDetail=null;
		// if(!(object==null)){
		// System.out.println(object);
		// userDetail=(UserDetailBean)object;
		// bean.setUserDetail(userDetail);
		// }

		return bean;
	}

	@Override
	public UserBean saveUserBean(UserBean user) throws Exception {
		// TODO Auto-generated method stub
		String id = (new GUID()).toString();
		user.setId(id);
		user.getUserDetail().setId(id);
		getSession().save(user);
		return user;
	}

	@Override
	public UserBean updateUserBean(UserBean user) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		if (LightsoftStringUtils.nullOrBlank(user.getPasswd())) {
			UserBean bean = (UserBean) session.createQuery(
					"from UserBean where id=?").setString(0, user.getId())
					.uniqueResult();
			// UserBean bean=getUserBeanById(user.getId());
			user.setPasswd(bean.getPasswd());
			user.setRePasswd(bean.getRePasswd());
			if (user.getUserDetail().getId() == null) {
				user.getUserDetail().setId(user.getId());
			}
			Object userDetailBean = session.createQuery(
					"from UserDetailBean where id=?").setString(0,
					user.getUserDetail().getId()).uniqueResult();
			if (logger.isDebugEnabled()) {
				logger.debug("updateUserBean.....................");
			}
			// System.out.println(userDetailBean);
			if (userDetailBean == null) {
				session.clear();
				UserDetailBean detailBean = user.getUserDetail();
				if (logger.isDebugEnabled()) {
					logger.debug("id..............." + detailBean.getId());
					logger.debug("height..............."
							+ detailBean.getHeight());
					logger.debug("weight..............."
							+ detailBean.getWeight());
				}
				session.save(detailBean);
			} else {
				session.clear();
				UserDetailBean detailBean = user.getUserDetail();
				session.update(detailBean);
			}
			session.clear();
		} else {
			user.setPasswd(MD5.getMD5(user.getPasswd().trim().getBytes()));
			user.setRePasswd(user.getPasswd());
		}
		session.saveOrUpdate(user);
		return user;
	}

	@Override
	public List<GroupBean> findGroupBeanByUserId(String id) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct g.groupId ID,g.groupname ");
		sb.append("  from v_role_user_group g ");
		sb.append(" where userId=? order by groupname ");

		return getSession().createSQLQuery(sb.toString()).addEntity(
				GroupBean.class).setString(0, id).list();
	}

	@Override
	public List<UserBean> findUserBeanByGroupId(String id) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("select distinct g.userId ID,g.nickname,g.username,g.email ");
		sb.append("  from v_role_user_group g ");
		sb.append(" where groupId=? order by username ");

		return getSession().createSQLQuery(sb.toString()).addEntity(
				UserBean.class).setString(0, id).list();
	}

	@Override
	public List<UserBean> findUserBeanByName(String name) throws Exception {
		// TODO Auto-generated method stub
		Criteria criteria = getSession().createCriteria(UserBean.class);

		criteria.add(Restrictions.eq("business", "1"));

		criteria.add(Restrictions.eq("recycled", "0"));

		if (!LightsoftStringUtils.nullOrBlank(name)) {
			criteria.add(Restrictions.like("nickName", name, MatchMode.END));
		}
		criteria.addOrder(Order.asc("nickName"));
		return criteria.list();
	}
}
